package com.darco.darcoapp;

import DARCOShared.requests.UpdateUserPositionRequest;
import DARCOShared.responses.ResponseBase;
import DARCOShared.responses.ResponseType;
import DARCOShared.responses.ResponseWrapper;
import DARCOShared.responses.UpdateUserPositionResponse;
import static DARCOShared.utils.Constants.*;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;

import com.darco.darcoapp.interfaces.IGeoLocatingActivity;

import eneter.messaging.endpoints.typedmessages.TypedResponseReceivedEventArgs;

public class UpdateLocation_Activity extends MessagingActivity implements IGeoLocatingActivity {
	public static final int FINISHED_SUCCESS = 10;
	public static final int FINISHED_FAILED = 11;

	GeolocationHelper myGeolocator;
	ContentValues account;
	MessagingManager mm;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		account = (ContentValues)(getIntent().getExtras().get("account"));

		setContentView(R.layout.activity_updateposition);

		myGeolocator = new GeolocationHelper(this);
		if(!myGeolocator.startGeoLocating())
			buildAlertMessageNoGps();

	}

	@Override
	public void onLocationObtained() {
		showLoadingDialog("Contacting server", "Location obtained, pushing update to server...");
		UpdateUserPositionRequest r = new UpdateUserPositionRequest(account.getAsString(ACCOUNT_EMAIL), 
				account.getAsString(ACCOUNT_PASSWORD),
				myGeolocator.getLatitude(),
				myGeolocator.getLongitude()
				);

		//update della posizione in account contentValues
		String lastLocation= ""+myGeolocator.getLatitude()+" "+ myGeolocator.getLongitude();
		account.put(ACCOUNT_LASTLOC, lastLocation);
		
		if(mm != null)
			mm.CloseConnection();
		
		mm = new MessagingManager();
		if(mm.ConnectToServer(this)){
			if(mm.SendRequest(r, this)){
				return;
			}
		}
		showFailedAlert("Failed to connect to server. Check that you have a working internet connection active on your device");
	}

	@Override
	void onResponseReceived(Object sender,	TypedResponseReceivedEventArgs<ResponseWrapper> e) {
		hideLoadingDialog();
		ResponseBase respbase = e.getResponseMessage().getResponse();
		if(respbase.getResponseType() == ResponseType.UpdateUserPosition){
			UpdateUserPositionResponse r = (UpdateUserPositionResponse)respbase;
			if(r.error)
				showFailedAlert(r.errorMessage);
			else
				showSuccessAlert();
		}

	}


	private void showSuccessAlert(){
		AlertDialog dialogBox = new AlertDialog.Builder(this).create();
		dialogBox.setTitle("Location update succesfull");
		dialogBox.setMessage("Your current position has been pinpointed and updated on the server.");
		dialogBox.setButton("Ok",  new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				//return to trading activity
				//finishActivity(why);
				Intent in = getIntent();
				setResult(FINISHED_SUCCESS, in);
				finish();
			}
		});
		dialogBox.show();
	}

	private void showFailedAlert(String message){
		AlertDialog dialogBox = new AlertDialog.Builder(this).create();
		dialogBox.setTitle("Location update failed");
		dialogBox.setMessage(message);
		dialogBox.setButton("Ok",  new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				//return to trading activity
				//finishActivity(why);
				Intent in = getIntent();
				setResult(FINISHED_FAILED, in);
				finish();
			}
		});
		dialogBox.show();
	}
	
	private void buildAlertMessageNoGps() {
	    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setMessage("Yout GPS seems to be disabled, do you want to enable it?")
	           .setCancelable(false)
	           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	               public void onClick(final DialogInterface dialog, final int id) {
	                   startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
	               }
	           })
	           .setNegativeButton("No", new DialogInterface.OnClickListener() {
	               public void onClick(final DialogInterface dialog, final int id) {
	                    dialog.cancel();
	                    finish();
	               }
	           });
	    final AlertDialog alert = builder.create();
	    alert.show();
	}
	
	

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(myGeolocator != null)
			myGeolocator.killLocationServices();
	}
}
